package com.jlhlyby.link;

/**
 * 234. 回文链表
 * 请判断一个链表是否为回文链表。
 *
 * 示例 1:
 *
 * 输入: 1->2
 * 输出: false
 * 示例 2:
 *
 * 输入: 1->2->2->1
 * 输出: true
 */
public class PalindromeLink {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(1);

        System.out.println(isPalindrome(head));

    }
    public static boolean isPalindrome(ListNode head) {
        if (head == null){
            return true;
        }
        ListNode middle = head;
        ListNode end = head;
        while ( end.next != null && end.next.next != null){
            middle = middle.next ;
            end = end.next.next;
        }

        end = reverseList(middle);
        while (head != null && head.next != end){
            if (head.val != end.val){
                return false;
            }
            head = head.next;
            end = end.next;
        }
        return true;

    }

    private static ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }
}
/**
 * 方法1.转换成数组双指针比较
 * 方法2.递归方法，加一个头指针
 * 方法3.改变后半部分的链表指针
 */
